<?php

namespace app\common\library;

use app\common\model\Config;
use app\common\model\Wechat as ModelWechat;
use EasyWeChat\Factory;

/**
 * 微信登录模型
 */
class Wechat
{

    protected $app;
    protected $config;

    public function __construct($platform)
    {
        $this->setConfig($platform);

        switch ($platform) {
            case 'wxOfficialAccount':  //微信公众号
                $this->app = Factory::officialAccount($this->config);
                break;
            case 'wxMiniProgram':      //微信小程序
                $this->app = Factory::miniProgram($this->config);
                break;
            case 'wxAppProgram':      //微信app

                break;
        }
    }
    //微信app登录
    public static function wxAppLogin($code)
    {
        $appid =  'wxd34dfb096708edde';
        $secret =  '8460b3fa982de157b5fa49e25e2a0a92';
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $secret . '&code=' . $code . '&grant_type=authorization_code';
        $response =  file_get_contents($url);
        $callback = json_decode($response, true);
        return $callback;
    }
    // 返回实例
    public function getApp()
    {
        return $this->app;
    }

    //小程序:获取openid&session_key
    public function code($code)
    {
        return $this->app->auth->session($code);
    }

    public function oauth()
    {
        return $this->app->oauth;
    }

    //解密信息
    public function decryptData($session, $iv, $encryptData)
    {
        return $this->app->encryptor->decryptData($session, $iv, $encryptData);
    }

    public function unify($orderBody)
    {
        return $this->app->order->unify($orderBody);
    }

    public function bridgeConfig($prepayId)
    {
        $jssdk = $this->app->jssdk;
        $config = $jssdk->bridgeConfig($prepayId, false);
        return $config;
    }

    public function notify()
    {
        return $this->app;
    }

    //获取accessToken
    public function getAccessToken()
    {
        $accessToken = $this->app->access_token;
        $token = $accessToken->getToken(); // token 数组 token['access_token'] 字符串
        return $token;
    }

    /**
     * 合并默认配置
     *
     * @param [type] $platform
     * @return void
     */
    private function setConfig($platform)
    {
        $wechat = ModelWechat::get(['type' => 'jsapi']);
        $debug = config('app_debug');
        $defaultConfig = [
            'app_id' => $wechat->appid,
            'secret' => $wechat->secret,
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
            'log' => [
                'default' => $debug ? 'dev' : 'prod', // 默认使用的 channel，生产环境可以改为下面的 prod
                'channels' => [
                    // 测试环境
                    'dev' => [
                        'driver' => 'single',
                        'path'   => ROOT_PATH . 'public/logs/wechat_login.log',
                        'level'  => 'debug',
                    ],
                    // 生产环境
                    'prod' => [
                        'driver' => 'daily',
                        'path'   => ROOT_PATH . 'public/logs/wechat_login.log',
                        'level'  => 'info',
                    ],
                ],
            ],
        ];

        $oauthConfig = [
            'oauth' => [
                'scopes'   => ['snsapi_userinfo'],
                'callback' => request()->domain() . '/api/User/wxOfficialAccountOauth'
            ],
        ];
        // 获取对应平台的配置
        // $this->config = Config::getEasyWechatConfig($platform);
        // 根据框架 debug 合并 log 配置
        $this->config = $defaultConfig;
        // 根据框架 平台 合并 oauth 配置
        if ($platform === 'wxOfficialAccount') {
            $this->config = array_merge($this->config, $oauthConfig);
        }
    }
}
